package com.fmboy.MXH.nav.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fmboy.MXH.nav.domain.dto.CategoryDTO;
import com.fmboy.MXH.nav.domain.entities.Category;
import com.fmboy.MXH.nav.domain.entities.Navigation;
import com.fmboy.MXH.nav.domain.pojo.CategoryVO;
import com.fmboy.MXH.nav.mapper.CategoryDTOMapper;
import com.fmboy.MXH.nav.service.CategoryService;
import com.fmboy.MXH.nav.utils.UserContext;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDTOMapper, Category> implements CategoryService {

    @Resource
    private CategoryDTOMapper categoryDTOMapper;
    @Resource
    private NavigationServiceImpl navigationService;

    @Override
    public List<CategoryVO> listByUserId(CategoryDTO categorydto) {
        Long userId = UserContext.getUserId();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<Category>().eq("user_id", userId);

        if (StringUtils.isNotBlank(categorydto.getCategory_name())) {
            // 根据分类名查询分类的逻辑 可以模糊查询
            queryWrapper.like("category_name", categorydto.getCategory_name());
        }

        if (StringUtils.isNotBlank(categorydto.getState())) {
            // 根据状态查询分类的逻辑
            queryWrapper.eq("state", categorydto.getState());
        }

        List<Category> categories = categoryDTOMapper.selectList(queryWrapper);
        return saveCategory(categories);
    }

    @Override
    public CategoryVO ByUserId(Integer id) {
        if (id == null) {
            throw new RuntimeException("ID不能位空");
        }
        Category byId = this.getById(id);
        CategoryVO categoryVO = new CategoryVO();
        if (byId != null) {
            BeanUtil.copyProperties(byId, categoryVO);
            categoryVO.setCategory_name(byId.getCategoryName());
            categoryVO.setCategory_text(byId.getCategoryText());
            categoryVO.setCreate_time(byId.getCreateTime());
            categoryVO.setUpdate_time(byId.getUpdateTime());

        }
        return categoryVO;
    }

    @Override
    public void saveCategory(CategoryDTO categoryDTO) {
        //使用hutool工具包进行判断实体类是否为空或者""
        if (categoryDTO == null || categoryDTO.getCategory_name().isEmpty()) {
            throw new RuntimeException("分类不能为空");
        }

        Category category = new Category();
        category.setUserId(Math.toIntExact(UserContext.getUserId()));
        category.setCategoryText(categoryDTO.getCategory_text());
        category.setCategoryName(categoryDTO.getCategory_name());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateTime(LocalDateTime.now());
        category.setSortOrder((int) (count() + 1));
        this.save(category);
    }

    @Override
    public void updateCategory(CategoryDTO categoryDTO) {

        // 空值检查
        if (categoryDTO.getCategory_name().isEmpty() || categoryDTO.getId() == null
        ) {
            throw new RuntimeException("修改失败,分类信息不能为空");
        }
        Category category = new Category();
        category.setId(categoryDTO.getId());
        category.setCategoryText(categoryDTO.getCategory_text());
        category.setCategoryName(categoryDTO.getCategory_name());
        category.setUpdateTime(LocalDateTime.now());
        category.setReason(categoryDTO.getReason());
        category.setSortOrder(CateGoryIndex(categoryDTO.getId()));
        this.updateById(category);
    }

    public List<CategoryVO> saveCategory(List<Category> categoryList) {
        List<CategoryVO> categoryVOList = new ArrayList<>();
        for (Category category : categoryList) {
            CategoryVO categoryVO = new CategoryVO();
            categoryVO.setId(category.getId());
            categoryVO.setCategory_name(category.getCategoryName());
            categoryVO.setState(category.getState());
            categoryVO.setCreate_time(category.getCreateTime());
            categoryVO.setUpdate_time(category.getUpdateTime());
            categoryVOList.add(categoryVO);
        }
        return categoryVOList;
    }

    @Override
    public void deleteById(Integer id) {
        //查询state状态是否为已发布
        Category category = this.getById(id);
        if (category.getState().equals("已发布")) {
            throw new RuntimeException("删除失败，此分类已发布，请先取消发布！");
        }
        if (category.getState().equals("待审核")) {
            throw new RuntimeException("删除失败，此分类待审核中，请先取消审核！");
        }
        //查询分类下是否有导航
        if (navigationService.count(new QueryWrapper<Navigation>().eq("category_id", id)) > 0) {
            throw new RuntimeException("删除失败，此分类下有导航，请先删除导航！");
        }
        this.removeById(id);

    }

    @Override
    public void updateCategoryState(CategoryDTO categoryDTO) {
        // 空值检查
        Objects.requireNonNull(categoryDTO, "CategoryDTO 不能为空");
        Objects.requireNonNull(categoryDTO.getId(), "ID 不能为空");
        Objects.requireNonNull(categoryDTO.getReason(), "Reason 不能为空");

        // 查询当前分类的状态
        QueryWrapper<Category> queryWrapper = new QueryWrapper<Category>().eq("id", categoryDTO.getId());
        Category category = categoryDTOMapper.selectOne(queryWrapper);

        if (category == null) {
            throw new RuntimeException("分类不存在");
        }

        String currentState = category.getState();
        String newState = determineNewState(currentState);

        if (newState == null) {
            throw new RuntimeException("未知的分类状态");
        }

        // 更新分类状态
        category.setState(newState);
        category.setUpdateTime(LocalDateTime.now());
        category.setReason(categoryDTO.getReason());
        categoryDTOMapper.updateById(category);
    }

    @Override
    public List<CategoryVO> AdminListByUserId(CategoryDTO categoryDTO) {
//        Long userId = UserContext.getUserId();
        QueryWrapper<Category> queryWrapper = new QueryWrapper<Category>();

        if (StringUtils.isNotBlank(categoryDTO.getCategory_name())) {
            // 根据分类名查询分类的逻辑 可以模糊查询
            queryWrapper.like("category_name", categoryDTO.getCategory_name());
        }

        if (StringUtils.isNotBlank(categoryDTO.getState())) {
            // 根据状态查询分类的逻辑
            queryWrapper.eq("state", categoryDTO.getState());
        }

        List<Category> categories = categoryDTOMapper.selectList(queryWrapper);
        return saveCategory(categories);

    }

    @Override
    public void AdminUpdateCategory(CategoryDTO categoryDTO) {
        if (categoryDTO.getId() == null) {
            throw new RuntimeException("分类ID不能为空");
        }

        Category byId = this.getById(categoryDTO.getId());
        if (byId == null) {
            throw new RuntimeException("分类不存在");
        }

        Category category = new Category();
        category.setId(categoryDTO.getId());
        category.setSortOrder(CateGoryIndex(categoryDTO.getId()));
        category.setCategoryName(categoryDTO.getCategory_name());
        category.setCategoryText(categoryDTO.getCategory_text());
        category.setUpdateTime(LocalDateTime.now());
        this.updateById(category);
    }

    @Override
    public void AdminUpdateCategoryState(CategoryDTO categoryDTO) {
        // 空值检查
        Objects.requireNonNull(categoryDTO, "CategoryDTO 不能为空");
        Objects.requireNonNull(categoryDTO.getId(), "ID 不能为空");
        Objects.requireNonNull(categoryDTO.getReason(), "Reason 不能为空");

        if (!(Set.of("已驳回", "待审核", "无", "已发布").contains(categoryDTO.getState()))) {
            throw new RuntimeException("未知的分类状态");
        }

        Category category = new Category();
        category.setId(categoryDTO.getId());
        category.setState(categoryDTO.getState());
        category.setReason(categoryDTO.getReason());
        category.setSortOrder(CateGoryIndex(categoryDTO.getId()));
        category.setUpdateTime(LocalDateTime.now());
        this.updateById(category);

    }

    @Override
    public void AdminUserById(Integer id) {
        //查询分类下是否有导航
        if (navigationService.count(new QueryWrapper<Navigation>().eq("category_id", id)) > 0) {
            throw new RuntimeException("删除失败，此分类下有导航，请先删除导航！");
        }
        this.removeById(id);
    }

    private String determineNewState(String currentState) {
        return switch (currentState) {
            case "无" -> "待审核";
            case "待审核", "已发布" -> "无";
            case "已驳回" -> "待审核";
            default -> null;
        };
    }

    public Integer CateGoryIndex(Integer id) {
        return this.getById(id).getSortOrder();
    }
}
